package com.yss.reportworld.service.impl;

import java.sql.Connection;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.yss.common.core.constant.RequestDataHelper;
import com.yss.common.core.enums.YssRegularEnum;
import com.yss.common.core.enums.YssStatusEnum;
import com.yss.common.core.exception.BusinessException;
import com.yss.common.core.utils.StringUtils;
import com.yss.common.core.utils.uuid.IdUtils;
import com.yss.common.security.utils.SecurityUtils;
import com.yss.reportworld.domain.*;
import com.yss.reportworld.enums.ReportWorldEnum;
import com.yss.reportworld.mapper.DataCustomerMapper;
import com.yss.reportworld.mapper.DataModularMapper;
import com.yss.reportworld.mapper.DataReportMapper;
import com.yss.reportworld.service.*;
import com.yss.reportworld.util.TableInfoUtil;
import lombok.extern.slf4j.Slf4j;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.datasource.ConnectionHolder;
import org.springframework.stereotype.Service;
import com.yss.reportworld.mapper.TableDetailMapper;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import javax.sql.DataSource;

/**
 * 表明细信息Service业务层处理
 *
 * @author yss
 * @date 2023-03-20
 */
@Slf4j
@Service
public class TableDetailServiceImpl extends ServiceImpl<TableDetailMapper, TableDetail> implements ITableDetailService {
    @Autowired
    private TableDetailMapper tableDetailMapper;
    @Autowired
    private IDatabaseCheckService databaseCheckService;
    @Qualifier("dataSource")
    @Autowired
    private DataSource dataSource;
    @Autowired
    private DataReportMapper dataReportMapper;
    @Autowired
    private DataModularMapper dataModularMapper;
    @Autowired
    private DataCustomerMapper dataCustomerMapper;

    /**
     * 查询表明细信息列表
     *
     * @param tableDetail 表明细信息
     * @return 表明细信息
     */
    @Override
    public List<TableDetail> selectTableDetailList(TableDetail tableDetail, boolean dataMark) {
        try {
            TableInfoUtil.handleTableVersion(tableDetail.getHisVersion()); // 替换表名
            QueryWrapper<TableDetail> wrapper = new QueryWrapper();
            if (StringUtils.isNotEmpty(tableDetail.getColumnName())) {
                wrapper.like("a.COLUMN_NAME", tableDetail.getColumnName());
            }
            if (StringUtils.isNotEmpty(tableDetail.getColumnChineseName())) {
                wrapper.like("a.COLUMN_CHINESE_NAME", tableDetail.getColumnChineseName());
            }
            if (null != tableDetail.getColumnType()) {
                wrapper.eq("a.COLUMN_TYPE", tableDetail.getColumnType());
            }
            if (StringUtils.isNotEmpty(tableDetail.getCodeName())) {
                wrapper.eq("a.CODE_NAME", tableDetail.getCodeName());
            }
            if (null != tableDetail.getBusinessPrimaryKey()) {
                wrapper.eq("a.BUSINESS_PRIMARY_KEY", tableDetail.getBusinessPrimaryKey());
            }
            if (null != tableDetail.getPrimaryKey()) {
                wrapper.eq("a.PRIMARY_KEY", tableDetail.getPrimaryKey());
            }
            if (null != tableDetail.getColumnLength()) {
                wrapper.eq("a.COLUMN_LENGTH", tableDetail.getColumnLength());
            }
            if (null != tableDetail.getColumnDecimal()) {
                wrapper.eq("a.COLUMN_DECIMAL", tableDetail.getColumnDecimal());
            }
            if (null != tableDetail.getColumnDefault()) {
                wrapper.eq("a.COLUMN_DEFAULT", tableDetail.getColumnDefault());
            }
            if (StringUtils.isNotEmpty(tableDetail.getTableId())) {
                wrapper.eq("a.TABLE_ID", tableDetail.getTableId());
            }
            if (null != tableDetail.getColumnNull()) {
                wrapper.eq("a.COLUMN_NULL", tableDetail.getColumnNull());
            }
            if (StringUtils.isNotEmpty(tableDetail.getId())) {
                wrapper.eq("a.ID", tableDetail.getId());
            }
            if (StringUtils.isNotEmpty(tableDetail.getVersion())) {
                wrapper.eq("a.VERSION", tableDetail.getVersion());
            }
            if (null != tableDetail.getStatus()) {
                wrapper.eq("a.STATUS", tableDetail.getStatus());
            }
            if (StringUtils.isNotEmpty(tableDetail.getStrReport())) {
                wrapper.in("b.REPORT_ID", tableDetail.getStrReport());
            }
            if (StringUtils.isNotEmpty(tableDetail.getStrModular())) {
                wrapper.in("c.MODULAR_ID", tableDetail.getStrModular());
            }
            if (StringUtils.isNotEmpty(tableDetail.getStrCustomer())) {
                wrapper.in("d.CUSTOMER_ID", tableDetail.getStrCustomer());
            }
            if (StringUtils.isNotEmpty(tableDetail.getTableName())) {
                wrapper.like("e.NAME", tableDetail.getTableName());
            }
            if (StringUtils.isNotEmpty(tableDetail.getTableChineseName())) {
                wrapper.like("e.CHINESE_NAME", tableDetail.getTableChineseName());
            }
            if (null != tableDetail.getLayered()) {
                wrapper.eq("e.LAYERED", tableDetail.getLayered());
            }
            // 导出的时候选择了数据，按照选择的数据
            if (StringUtils.isNotEmpty(tableDetail.getIds())) {
                List<String> list = JSONArray.parseArray(tableDetail.getIds(), String.class);
                if(StringUtils.isNotEmpty(list)) {
                    wrapper.in("a.ID", list);
                }
            }
            List<TableDetail> list = tableDetailMapper.queryTableDetail(wrapper);
            if (StringUtils.isEmpty(list)) {
                return list;
            }
            if (dataMark) {
                for (TableDetail detail : list) {
                    this.setTableDetailInfo(detail);
                }
            }
            return list;
        } finally {
            RequestDataHelper.removeThreadLocal();
        }
    }

    private void setTableDetailInfo(TableDetail tableDetailInfo) {
        // 所属模块
        DataModular modular = new DataModular();
        modular.setDataId(tableDetailInfo.getId());
        modular.setDataCode(ReportWorldEnum.REPORT_TABLE_DETAIL_CODE.getCode());
        List<DataModular> listModular = dataModularMapper.selectPrimaryByDataId(modular);
        if (StringUtils.isNotEmpty(listModular)) {
            StringBuffer modularName = new StringBuffer();
            for (DataModular dataModular : listModular) {
                modularName.append(dataModular.getModularName()).append("/");
            }
            tableDetailInfo.setStrModularName(modularName.deleteCharAt(modularName.length() - 1).toString());
            tableDetailInfo.setStrModular(listModular.stream().map(DataModular::getModularId).collect(Collectors.toList()));
        }
        // 所属客户
        DataCustomer customer = new DataCustomer();
        customer.setDataId(tableDetailInfo.getId());
        customer.setDataCode(ReportWorldEnum.REPORT_TABLE_DETAIL_CODE.getCode());
        List<DataCustomer> listCustomer = dataCustomerMapper.selectPrimaryByDataId(customer);
        if (StringUtils.isNotEmpty(listCustomer)) {
            StringBuffer customerName = new StringBuffer();
            for (DataCustomer dataCustomer : listCustomer) {
                customerName.append(dataCustomer.getCustomerName()).append("/");
            }
            tableDetailInfo.setStrCustomerName(customerName.deleteCharAt(customerName.length() - 1).toString());
            tableDetailInfo.setStrCustomer(listCustomer.stream().map(DataCustomer::getCustomerId).collect(Collectors.toList()));
        }
        // 所属报表
        DataReport report = new DataReport();
        report.setDataId(tableDetailInfo.getId());
        report.setDataCode(ReportWorldEnum.REPORT_TABLE_DETAIL_CODE.getCode());
        List<DataReport> listReport = dataReportMapper.selectPrimaryByDataId(report);
        if (StringUtils.isNotEmpty(listReport)) {
            StringBuffer reportName = new StringBuffer();
            for (DataReport dataReport : listReport) {
                reportName.append(dataReport.getReportName()).append("/");
            }
            tableDetailInfo.setStrReportName(reportName.deleteCharAt(reportName.length() - 1).toString());
            tableDetailInfo.setStrReport(listReport.stream().map(DataReport::getReportId).collect(Collectors.toList()));
        }
    }

    /**
     * 获取 字段详细信息  ，包含字段所属客户，模块。客户
     *
     * @param tableDetail
     * @return
     */
    public TableDetail selectTableDetailById(TableDetail tableDetail) {
        try {
            TableInfoUtil.handleTableVersion(tableDetail.getHisVersion()); // 替换表名
            QueryWrapper<TableDetail> wrapper = new QueryWrapper<>();
            wrapper.eq("a.ID", tableDetail.getId());
            List<TableDetail> list = tableDetailMapper.queryTableDetail(wrapper);
            if (StringUtils.isEmpty(list) || StringUtils.isNull(list.get(0))) {
                return null;
            }
            TableDetail detail = list.get(0);
            this.setTableDetailInfo(detail);
            return detail;
        } finally {
            RequestDataHelper.removeThreadLocal();
        }
    }


    /**
     * 添加表信息
     *
     * @param tableDetail
     * @return
     */
    @Override
    @Transactional
    public void addTableDetail(TableDetail tableDetail) {
        try {
            if (!this.checkTableDetailColumnNameUnique(tableDetail)) {
                throw new BusinessException("表字段名称【" + tableDetail.getColumnName() + "】已存在");
            }
            if (tableDetail.getColumnName().equals(tableDetail.getOriginalColumnName())) {
                throw new BusinessException("表字段和来源字段不能一致");
            }
            tableDetail.setId(IdUtils.fastSimpleUUID());
            tableDetail.setCreateBy(SecurityUtils.getUsername());
            tableDetail.setCreateTime(new Date());
            tableDetail.setColumnName(tableDetail.getColumnName().toUpperCase());
            this.checkColumnDefault(tableDetail);
            this.addTableDetailInfo(tableDetail);
            this.updateOriginalColumName(tableDetail);
            // 查询最大序号
            QueryWrapper<TableDetail> wrapper = new QueryWrapper<>();
            wrapper.select("MAX(ORDER_NUM) AS ORDER_NUM");
            wrapper.eq("TABLE_ID", tableDetail.getTableId());
            TableDetail detail = this.getOne(wrapper);
            Integer sequence = 1;
            if (null != detail && null != detail.getOrderNum()) {
                sequence = detail.getOrderNum() + 1;
            }
            tableDetail.setOrderNum(sequence);
            tableDetailMapper.insert(tableDetail);
            ConnectionHolder holder = (ConnectionHolder) TransactionSynchronizationManager.getResource(this.dataSource);
            Connection connection = holder.getConnection();
            if (null == connection) {
                throw new BusinessException("获取数据库连接出错，请稍后重试！");
            }
            String msgInfo = databaseCheckService.checkDataBaseAllByCode(ReportWorldEnum.REPORT_TABLE_DETAIL_CODE.getDesc(), connection, "");
            if (StringUtils.isNotEmpty(msgInfo)) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                throw new BusinessException(msgInfo);
            }
        } finally {
            RequestDataHelper.removeThreadLocal();
        }
    }

    /**
     * 修改表信息
     *
     * @param tableDetail
     * @return
     */
    @Override
    @Transactional
    public void editTableDetail(TableDetail tableDetail) {
        try {
            TableInfoUtil.handleTableVersion(tableDetail.getHisVersion()); // 替换表名
            if (!this.checkTableDetailColumnNameUnique(tableDetail)) {
                throw new BusinessException("表字段名称【" + tableDetail.getColumnName() + "】已存在");
            }
            if (tableDetail.getColumnName().equals(tableDetail.getOriginalColumnName())) {
                throw new BusinessException("表字段和来源字段不能一致");
            }
            tableDetail.setUpdateTime(new Date());
            tableDetail.setUpdateBy(SecurityUtils.getUsername());
            tableDetail.setColumnName(tableDetail.getColumnName().toUpperCase());
            this.checkColumnDefault(tableDetail);
            //删除表和客户信息关联关系
            QueryWrapper<DataCustomer> wrapperCustomer = new QueryWrapper<>();
            wrapperCustomer.in("DATA_ID", tableDetail.getId());
            wrapperCustomer.eq("DATA_CODE", ReportWorldEnum.REPORT_TABLE_DETAIL_CODE.getCode());
            dataCustomerMapper.delete(wrapperCustomer);
            //删除表和模块信息关联关系
            QueryWrapper<DataModular> wrapperModular = new QueryWrapper<>();
            wrapperModular.in("DATA_ID", tableDetail.getId());
            wrapperModular.eq("DATA_CODE", ReportWorldEnum.REPORT_TABLE_DETAIL_CODE.getCode());
            dataModularMapper.delete(wrapperModular);
            //删除表和报表信息关联关系
            QueryWrapper<DataReport> wrapperReport = new QueryWrapper<>();
            wrapperReport.in("DATA_ID", tableDetail.getId());
            wrapperReport.eq("DATA_CODE", ReportWorldEnum.REPORT_TABLE_DETAIL_CODE.getCode());
            dataReportMapper.delete(wrapperReport);
            this.addTableDetailInfo(tableDetail);
            this.updateOriginalColumName(tableDetail);
            this.updateById(tableDetail);
            ConnectionHolder holder = (ConnectionHolder) TransactionSynchronizationManager.getResource(this.dataSource);
            Connection connection = holder.getConnection();
            if (null == connection) {
                throw new BusinessException("获取数据库连接出错，请稍后重试！");
            }
            String msgInfo = databaseCheckService.checkDataBaseAllByCode(ReportWorldEnum.REPORT_TABLE_DETAIL_CODE.getDesc(), connection, "");
            if (StringUtils.isNotEmpty(msgInfo)) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                throw new BusinessException(msgInfo);
            }
        } finally {
            RequestDataHelper.removeThreadLocal();
        }
    }

    /**
     * 检查表字段默认值
     *
     * @param tableDetail
     */
    public void checkColumnDefault(TableDetail tableDetail) {
        if (null == tableDetail || StringUtils.isBlank(tableDetail.getColumnDefault())) {
            return;
        }
        String defaultVlaue = tableDetail.getColumnDefault();
        // 字符型
        if (1 == tableDetail.getColumnType() || 4 == tableDetail.getColumnType() || 7 == tableDetail.getColumnType() ||
                8 == tableDetail.getColumnType() || 9 == tableDetail.getColumnType() || 10 == tableDetail.getColumnType()) {
            if (!StringUtils.oneOf(defaultVlaue.toUpperCase(), "SYS_GUID,TO_CHAR")
                    && !(defaultVlaue.startsWith("'") && defaultVlaue.endsWith("'"))) {
                throw new BusinessException("字段类型为字符型，默认值也必须为字符类型，或者函数【SYS_GUID,TO_CHAR】，请检查确认！");
            }
        }
        //整数
        if (2 == tableDetail.getColumnType() || 11 == tableDetail.getColumnType()) {
            if (!Pattern.matches(YssRegularEnum.NUMBER.getCode(), defaultVlaue)) {
                throw new BusinessException("字段类型的整数类型，默认值也必须为整数类型，请检查确认！");
            }
        }
        // 非整数数据
        if (3 == tableDetail.getColumnType() || 12 == tableDetail.getColumnType()) {
            if (!Pattern.matches(YssRegularEnum.NUMBER.getCode(), defaultVlaue) && !Pattern.matches(YssRegularEnum.FLOAT.getCode(), defaultVlaue)) {
                throw new BusinessException("字段类型的数字类型，默认值也必须为数字类型，请检查确认！");
            }
        }
        // 时间类型
        if (5 == tableDetail.getColumnType() || 6 == tableDetail.getColumnType()) {
            if (!StringUtils.oneOf(defaultVlaue.toUpperCase(), "TO_DATE,TO_TIMESTAMP,SYSTIMESTAMP,TIMESTAMP,SYSDATE")) {
                throw new BusinessException("字段类型时间类型，默认值必须为时间类型的函数【TO_DATE,TO_TIMESTAMP,SYSTIMESTAMP,TIMESTAMP,SYSDATE】，请检查确认！");
            }
        }
    }

    /**
     * 校验表字段名称是否唯一
     *
     * @param tableDetail
     * @return 结果
     */
    private boolean checkTableDetailColumnNameUnique(TableDetail tableDetail) {
        String tableDetailId = StringUtils.isNull(tableDetail.getId()) ? "-1" : tableDetail.getId();
        QueryWrapper<TableDetail> wrapper = new QueryWrapper<>();
        wrapper.eq("TABLE_ID", tableDetail.getTableId());
        wrapper.eq("COLUMN_NAME", tableDetail.getColumnName());
        TableDetail info = this.getOne(wrapper);
        if (StringUtils.isNotNull(info) && !info.getId().equals(tableDetailId)) {
            return false;
        }
        return true;
    }

    /**
     * 保存表的关联关系信息
     */
    private void addTableDetailInfo(TableDetail detail) {
        if (StringUtils.isNotEmpty(detail.getStrCustomer())) {
            for (String str : detail.getStrCustomer()) {
                DataCustomer dataCustomer = new DataCustomer();
                dataCustomer.setId(IdUtils.fastSimpleUUID());
                dataCustomer.setCustomerId(str);
                dataCustomer.setDataId(detail.getId());
                dataCustomer.setDataCode(ReportWorldEnum.REPORT_TABLE_DETAIL_CODE.getCode());
                dataCustomerMapper.insert(dataCustomer);
            }
        }
        if (StringUtils.isNotEmpty(detail.getStrModular())) {
            for (String str : detail.getStrModular()) {
                DataModular dataModular = new DataModular();
                dataModular.setId(IdUtils.fastSimpleUUID());
                dataModular.setModularId(str);
                dataModular.setDataId(detail.getId());
                dataModular.setDataCode(ReportWorldEnum.REPORT_TABLE_DETAIL_CODE.getCode());
                dataModularMapper.insert(dataModular);
            }
        }
        if (StringUtils.isNotEmpty(detail.getStrReport())) {
            for (String str : detail.getStrReport()) {
                DataReport dataReport = new DataReport();
                dataReport.setId(IdUtils.fastSimpleUUID());
                dataReport.setReportId(str);
                dataReport.setDataId(detail.getId());
                dataReport.setDataCode(ReportWorldEnum.REPORT_TABLE_DETAIL_CODE.getCode());
                dataReportMapper.insert(dataReport);
            }
        }
    }

    /**
     * 增加修改前字段信息的时候，以前的字段状态标识为已删除状态
     *
     * @param tableDetail
     */
    private void updateOriginalColumName(TableDetail tableDetail) {
        if (null == tableDetail || StringUtils.isBlank(tableDetail.getTableId()) || StringUtils.isBlank(tableDetail.getOriginalColumnName())) {
            return;
        }
        // 查询以前字段的信息修改状态
        QueryWrapper<TableDetail> wrapper = new QueryWrapper<>();
        wrapper.eq("COLUMN_NAME", tableDetail.getOriginalColumnName());
        wrapper.eq("TABLE_ID", tableDetail.getTableId());
        TableDetail detail = this.getOne(wrapper);
        if (null == detail || StringUtils.isBlank(detail.getId())) {
            throw new BusinessException("获取修改前表字段信息失败，请稍后重试！");
        }
        detail.setUpdateTime(new Date());
        detail.setUpdateBy(SecurityUtils.getUsername());
        detail.setStatus(YssStatusEnum.DELETED.getCode());
        this.updateById(detail);
    }


    /**
     * 删除表字段信息
     *
     * @param tableDetail
     */
    @Transactional
    public boolean delReportTableDetail(TableDetail tableDetail) {
        try {
            TableInfoUtil.handleTableVersion(tableDetail.getHisVersion()); // 替换表名
            //删除表和客户信息关联关系
            QueryWrapper<DataCustomer> wrapperCustomer = new QueryWrapper<>();
            wrapperCustomer.in("DATA_ID", tableDetail.getIdList());
            wrapperCustomer.eq("DATA_CODE", ReportWorldEnum.REPORT_TABLE_DETAIL_CODE.getCode());
            dataCustomerMapper.delete(wrapperCustomer);
            //删除表和模块信息关联关系
            QueryWrapper<DataModular> wrapperModular = new QueryWrapper<>();
            wrapperModular.in("DATA_ID", tableDetail.getIdList());
            wrapperModular.eq("DATA_CODE", ReportWorldEnum.REPORT_TABLE_DETAIL_CODE.getCode());
            dataModularMapper.delete(wrapperModular);
            //删除表和报表信息关联关系
            QueryWrapper<DataReport> wrapperReport = new QueryWrapper<>();
            wrapperReport.in("DATA_ID", tableDetail.getIdList());
            wrapperReport.eq("DATA_CODE", ReportWorldEnum.REPORT_TABLE_DETAIL_CODE.getCode());
            dataReportMapper.delete(wrapperReport);
            return this.removeByIds(tableDetail.getIdList());
        } finally {
            RequestDataHelper.removeThreadLocal();
        }
    }

    /**
     * 批量修改表字段信息
     *
     * @param tableDetail
     */
    @Transactional
    public void batchUpdateTableInfoDetail(TableDetail tableDetail) {
        if (null == tableDetail || StringUtils.isEmpty(tableDetail.getIdList())) {
            throw new BusinessException("获取批量修改数据信息失败，请稍后重试！");
        }
        try {
            TableInfoUtil.handleTableVersion(tableDetail.getHisVersion()); // 替换表名
            for (String id : tableDetail.getIdList()) {
                if (StringUtils.isBlank(id)) {
                    continue;
                }
                tableDetail.setId(id);
                // 批量修改了对应的模块 客户 报表，就先删除在插入
                if (StringUtils.isNotEmpty(tableDetail.getStrCustomer()) || tableDetail.isClearCustomer()) {
                    //删除表和客户信息关联关系
                    QueryWrapper<DataCustomer> wrapperCustomer = new QueryWrapper<>();
                    wrapperCustomer.in("DATA_ID", tableDetail.getId());
                    wrapperCustomer.eq("DATA_CODE", ReportWorldEnum.REPORT_TABLE_DETAIL_CODE.getCode());
                    dataCustomerMapper.delete(wrapperCustomer);
                }
                if (StringUtils.isNotEmpty(tableDetail.getStrModular()) || tableDetail.isClearModular()) {
                    //删除表和模块信息关联关系
                    QueryWrapper<DataModular> wrapperModular = new QueryWrapper<>();
                    wrapperModular.in("DATA_ID", tableDetail.getId());
                    wrapperModular.eq("DATA_CODE", ReportWorldEnum.REPORT_TABLE_DETAIL_CODE.getCode());
                    dataModularMapper.delete(wrapperModular);
                }
                if (StringUtils.isNotEmpty(tableDetail.getStrReport()) || tableDetail.isClearReport()) {
                    //删除表和报表信息关联关系
                    QueryWrapper<DataReport> wrapperReport = new QueryWrapper<>();
                    wrapperReport.in("DATA_ID", tableDetail.getId());
                    wrapperReport.eq("DATA_CODE", ReportWorldEnum.REPORT_TABLE_DETAIL_CODE.getCode());
                    dataReportMapper.delete(wrapperReport);
                }
                this.addTableDetailInfo(tableDetail);  // 保存表字段对应的客户，模块，报表信息
                TableDetail detail = new TableDetail();
                UpdateWrapper<TableDetail> wrapper = new UpdateWrapper<>();
                wrapper.eq("ID", tableDetail.getId());
                boolean falg = false;
                detail.setId(id);
                if (StringUtils.isNotBlank(tableDetail.getColumnName())) {
                    detail.setColumnName(tableDetail.getColumnName());
                    falg = true;
                }
                if (StringUtils.isNotBlank(tableDetail.getColumnChineseName())) {
                    detail.setColumnChineseName(tableDetail.getColumnChineseName());
                    falg = true;
                }
                if (null != tableDetail.getColumnType()) {
                    detail.setColumnType(tableDetail.getColumnType());
                    falg = true;
                }
                if (null != tableDetail.getPrimaryKey()) {
                    detail.setPrimaryKey(tableDetail.getPrimaryKey());
                    falg = true;
                }
                if (null != tableDetail.getBusinessPrimaryKey()) {
                    detail.setBusinessPrimaryKey(tableDetail.getBusinessPrimaryKey());
                    falg = true;
                }
                if (null != tableDetail.getColumnLength()) {
                    detail.setColumnLength(tableDetail.getColumnLength());
                    falg = true;
                }
                if (null != tableDetail.getColumnDecimal()) {
                    detail.setColumnDecimal(tableDetail.getColumnDecimal());
                    falg = true;
                }
                if (StringUtils.isNotBlank(tableDetail.getRemark())) {
                    detail.setRemark(tableDetail.getRemark());
                    falg = true;
                }
                if (null != tableDetail.getColumnNull()) {
                    detail.setColumnNull(tableDetail.getColumnNull());
                    falg = true;
                }
                if (StringUtils.isNotBlank(tableDetail.getColumnDefault())) {
                    detail.setColumnDefault(tableDetail.getColumnDefault());
                    falg = true;
                }
                if (StringUtils.isNotBlank(tableDetail.getVersion())) {
                    detail.setVersion(tableDetail.getVersion());
                    falg = true;
                }
                if (StringUtils.isNotBlank(tableDetail.getCodeName())) {
                    detail.setCodeName(tableDetail.getCodeName());
                    falg = true;
                }
                if (null != tableDetail.getStatus()) {
                    detail.setStatus(tableDetail.getStatus());
                    falg = true;
                }
                if (falg) {
                    detail.setUpdateTime(new Date());
                    detail.setUpdateBy(SecurityUtils.getUsername());
                    this.update(detail, wrapper);
                }
            }
            ConnectionHolder holder = (ConnectionHolder) TransactionSynchronizationManager.getResource(this.dataSource);
            Connection connection = holder.getConnection();
            if (null == connection) {
                throw new BusinessException("获取数据库连接出错，请稍后重试！");
            }
            String msgInfo = databaseCheckService.checkDataBaseAllByCode(ReportWorldEnum.REPORT_TABLE_DETAIL_CODE.getDesc(), connection, "");
            if (StringUtils.isNotEmpty(msgInfo)) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                throw new BusinessException(msgInfo);
            }
        } finally {
            RequestDataHelper.removeThreadLocal();
        }
    }

    /**
     * 修改顺序
     *
     * @param list
     */
    public void handleUpdateOrderNum(List<TableDetail> list) {
        try {
            TableInfoUtil.handleTableVersion(list.get(0).getHisVersion()); // 替换表名
            this.updateBatchById(list);
        } finally {
            RequestDataHelper.removeThreadLocal();
        }
    }
}
